package com.example.demo.Controller;

import com.example.demo.Entity.Question;
import com.example.demo.Service.QuestionService;
import com.example.demo.Service.SysUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/admin")

public class AdminController {
    @Autowired
    private QuestionService questionService;


    @RequestMapping("/addQuestion")
    @RequiresRoles("admin")
    public String addQuestion(@RequestParam("question")String question,@RequestParam("answer")String answer){
        questionService.addQuestion(question,answer);
        return "redirect:/admin/list";
    }

    @RequestMapping("/updateQuestion")
    @RequiresRoles("admin")
    public String updateQuestion(@RequestParam("id")Integer id,@RequestParam("question")String question,@RequestParam("answer")String answer){
        questionService.updateQuestion(id,question,answer);
        return "redirect:/admin/list";
    }

    @RequestMapping("/deleteQuestion")
    @RequiresRoles("admin")
    public String deleteQuestion(@RequestParam("id")Integer id){
        questionService.deleteQuestion(id);
        return "redirect:/admin/list";
    }



    @RequiresRoles("admin")
    @RequestMapping("/list")
    public String admin(Model model, @RequestParam(defaultValue = "1")Integer pageNum, @RequestParam(defaultValue = "15")Integer pageSize){

        Page<Object> objects = PageHelper.startPage(pageNum, pageSize);

        List<Question> questions=questionService.findAll();
        PageInfo<Question> pageInfo=new PageInfo<Question>(questions);
        //pageInfo.setList(questions);

        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("pageNum",pageInfo.getPageNum());
        model.addAttribute("pageSize",pageInfo.getPageSize());


        model.addAttribute("totalPages",pageInfo.getPages());
        model.addAttribute("isFirstPage",pageInfo.isIsFirstPage());
        model.addAttribute("isLastPage",pageInfo.isIsLastPage());
        return "admin";
    }

}
